package org.catpay.modules.sys.oauth2;

import java.util.Collection;
import java.util.Set;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.catpay.common.utils.JsonUtil;
import org.catpay.common.utils.RedisUtils;

public class RedisCache<K,V> implements Cache<K,V> {

	private long expireTime;
	
	private RedisUtils redisUtils;
	
	public RedisCache(long expireTime, RedisUtils redisUtils) {
		this.expireTime = expireTime;
		this.redisUtils = redisUtils;
	}

	@Override
	public void clear() throws CacheException {
		
	}

	@Override
	public V get(K arg0) throws CacheException {
		String key = null;
		if(arg0 instanceof SimplePrincipalCollection) {
			SimplePrincipalCollection simplePrincipalCollection =(SimplePrincipalCollection) arg0;
			key = JsonUtil.getInstance().obj2json(simplePrincipalCollection.getPrimaryPrincipal());
		}else
			key = JsonUtil.getInstance().obj2json(arg0);
		return (V) redisUtils.getObj(key, expireTime);
	}

	@Override
	public Set<K> keys() {
		return null;
	}

	@Override
	public V put(K arg0, V arg1) throws CacheException {
		String key = null;
		if(arg0 instanceof SimplePrincipalCollection) {
			SimplePrincipalCollection simplePrincipalCollection =(SimplePrincipalCollection) arg0;
			key = JsonUtil.getInstance().obj2json(simplePrincipalCollection.getPrimaryPrincipal());
		}else
			key = JsonUtil.getInstance().obj2json(arg0);
		redisUtils.setObj(key, arg1, expireTime);
		return arg1;
	}

	@Override
	public V remove(K arg0) throws CacheException {
		String key = null;
		if(arg0 instanceof SimplePrincipalCollection) {
			SimplePrincipalCollection simplePrincipalCollection =(SimplePrincipalCollection) arg0;
			key = JsonUtil.getInstance().obj2json(simplePrincipalCollection.getPrimaryPrincipal());
		}else
			key = JsonUtil.getInstance().obj2json(arg0);
		redisUtils.delete(key);
		return null;
	}

	@Override
	public int size() {
		return 0;
	}

	@Override
	public Collection<V> values() {
		return null;
	}

}
